package com.example.pkmedical.Fragments;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.pkmedical.APP.MyApp;
import com.example.pkmedical.Activity.rollovershock.RolloverShockCantStartActivity;
import com.example.pkmedical.Activity.rollovershock.RolloverShockNextActivity;
import com.example.pkmedical.Activity.warning.BedPosLockActivity;
import com.example.pkmedical.Activity.warning.LeaveBedNoVoiceActivity;
import com.example.pkmedical.Activity.warning.WarningCenterActivity;
import com.example.pkmedical.Activity.warning.WarningLeftTopActivity;
import com.example.pkmedical.Activity.warning.WeightTooSmallActivity;
import com.example.pkmedical.Base.BaseFragment;
import com.example.pkmedical.Event.MessageWrap;
import com.example.pkmedical.R;
import com.example.pkmedical.Utils.CommandUtil;
import com.example.pkmedical.Utils.DistinguishUtil;
import com.example.pkmedical.Utils.FinishActivityManager;
import com.example.pkmedical.Utils.SPUtils;
import com.example.pkmedical.Utils.SerialProtUtil;

import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;

public class HomeFragment extends BaseFragment {
    private static final String TAG = "yangshuo";
    byte[] mBytes;
    @BindView(R.id.homebed_bed)
    ImageView homebedBed;
    @BindView(R.id.angle_num_text)
    TextView angleNumText;
    @BindView(R.id.home_fragment_zerotime)
    TextView homeFragmentZerotime;
    @BindView(R.id.home_fragment_pingfang)
    TextView homeFragmentPingfang;
    int mAngleFu = 0;
    @BindView(R.id.home_fragment_pingfang_img)
    ImageView homeFragmentPingfangImg;
    @BindView(R.id.home_fragment_qdms_img)
    ImageView homeFragmentQdmsImg;
    @BindView(R.id.headyilt_img)
    ImageView headyilt_img;
    @BindView(R.id.home_fragment_leavebed_img)
    ImageView home_fragment_leavebed_img;

    @BindView(R.id.home_fragment_leavebed_text)
    TextView home_fragment_leavebed_text;
    @BindView(R.id.home_fragment_qdms_text)
    TextView homeFragmentQdmsText;
    @BindView(R.id.homebed_bed_up)
    ImageView homebedBedUp;
    @BindView(R.id.home_fragment_zeroimg)
    ImageView homeFragmentZeroimg;
    private int weightOne, weightTwo, weightThree, weightfour, weightAll;
    private Activity RolloverShockNextActivity;

    @Override
    public int setLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    public void findViewById(View view) {

    }

    @Override
    public void onResume() {
        super.onResume();
        switch (CommandUtil.ZERO_TYPE) {
            case 0:
                homeFragmentZerotime.setText(getString(R.string.home_zerod_no));
                break;
            case 1:
                homeFragmentZerotime.setText(getString(R.string.home_zerod) + SPUtils.getInstance().getString("TOZERO_DATA"));
                homeFragmentZeroimg.setImageResource(R.drawable.img_main_zero_green_new);
                TimeCountFS();
                break;
            case 2:
                homeFragmentZerotime.setText(getString(R.string.home_zerod) + SPUtils.getInstance().getString("NEWUSER_ZERO_DATA"));
                homeFragmentZeroimg.setImageResource(R.drawable.img_main_zero_green_new);
                TimeCountFS();
                break;
            case 3:

                break;
        }

        switch (CommandUtil.HEAD_WARNING_TYPE) {
            case 0:
                headyilt_img.setImageResource(R.drawable.img_home_headtilt_close);
                break;

            case 1:
                headyilt_img.setImageResource(R.drawable.img_home_headtilt_thirty);
                break;

            case 2:
                headyilt_img.setImageResource(R.drawable.img_home_headtilt_fortyfive);
                break;
        }
        switch (CommandUtil.LEAVEBED_TYPE) {
            case 0:
                home_fragment_leavebed_img.setImageResource(R.drawable.img_home_lcgb_off);
                home_fragment_leavebed_text.setText(getString(R.string.home_lcgb));
                break;

            case 1:
                home_fragment_leavebed_img.setImageResource(R.drawable.img_home_leavebed_pos);
                home_fragment_leavebed_text.setText(getString(R.string.warning_position));
                break;

            case 2:
                home_fragment_leavebed_img.setImageResource(R.drawable.img_home_leavebed_ing);
                home_fragment_leavebed_text.setText(getString(R.string.leaveing_bed));
                break;

            case 3:
                home_fragment_leavebed_img.setImageResource(R.drawable.img_home_leavebed_ok);
                home_fragment_leavebed_text.setText(getString(R.string.leaved_bed));
                break;

        }
    }

    @Override
    public void setViewData(View view) {
        SerialProtUtil.getInstance().sendBytes50(2, CommandUtil.APP_STARTED);
        SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.REQUEST_IS_CUSHION);
        SerialProtUtil.getInstance().sendBytes300(2, CommandUtil.GET_BED_ANGLE);
        SerialProtUtil.getInstance().sendBytes400(2, CommandUtil.GET_RAIL_STATE);


    }

    @Override
    public void setClickEvent(View view) {

    }

    @Override
    protected boolean isRegisteredEventBus() {
        return true;
    }

    @Override
    public void onReceiveEvent(MessageWrap event) {
        super.onReceiveEvent(event);
        mBytes = event.getBytes();
        if (event.getCode() == MessageWrap.RAIL_STATE) {
            Log.d(TAG, "onDataReceivedrail_STATE [ byte[] ]: " + Arrays.toString(event.getBytes()));
            distinguish(mBytes);
        } else if (event.getCode() == MessageWrap.QIDIANMOSHI) {
            distinguishqdms(mBytes);
        } else if (event.getCode() == MessageWrap.SHUSHIMOSHI) {
            homeFragmentQdmsImg.setImageResource(R.drawable.img_home_shushi);
            homeFragmentQdmsText.setText(getString(R.string.routine_ssms));
            homebedBedUp.setVisibility(View.GONE);
        }
//        else if (event.getCode() == MessageWrap.CUSHION_NOHAVE) {
//
//        }
    }


    /**
     * 返回数据识别0:放下，1：抬起
     */
    private void distinguishqdms(byte[] bytes) {

        if (DistinguishUtil.distinguishUtil(bytes)) {
            homebedBedUp.setVisibility(View.GONE);

            switch (bytes[3]) {
                case 0x01:
                    homeFragmentQdmsImg.setImageResource(R.drawable.img_home_changgui_on);
                    homeFragmentQdmsText.setText(getString(R.string.routine_cgms));
                    break;
                case 0x02:
                    homeFragmentQdmsImg.setImageResource(R.drawable.img_home_sleep);
                    homeFragmentQdmsText.setText(getString(R.string.routine_smms));
                    homebedBedUp.setImageResource(R.drawable.img_homebed_zz);
                    homebedBedUp.setVisibility(View.VISIBLE);
                    break;
                case 0x03:
                    homeFragmentQdmsImg.setImageResource(R.drawable.img_home_zuida);
                    homeFragmentQdmsText.setText(getString(R.string.routine_zdcq));
                    if (CommandUtil.IS_ROLLOVEW_SHOCK) {
                        SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.CEFAN_STOP);
                        FinishActivityManager.getManager().finishActivity(RolloverShockNextActivity.class);
                    }
                    break;
                case 0x04:
                    homeFragmentQdmsImg.setImageResource(R.drawable.img_home_tunbu);
                    homeFragmentQdmsText.setText(getString(R.string.routine_tbfq));
                    homebedBedUp.setImageResource(R.drawable.img_homebed_pg);
                    homebedBedUp.setVisibility(View.VISIBLE);
                    homebedBedUp.setImageResource(R.drawable.img_homebed_tbfq);
                    break;
                case 0x05:
                    homeFragmentQdmsImg.setImageResource(R.drawable.img_home_left);
                    homeFragmentQdmsText.setText(getString(R.string.routine_zfms));
                    homebedBedUp.setImageResource(R.drawable.img_homebed_left);
                    homebedBedUp.setVisibility(View.VISIBLE);
                    break;
                case 0x06:
                    homeFragmentQdmsImg.setImageResource(R.drawable.img_home_right);
                    homeFragmentQdmsText.setText(getString(R.string.routine_yfms));
                    homebedBedUp.setImageResource(R.drawable.img_homebed_right);
                    homebedBedUp.setVisibility(View.VISIBLE);
                    break;
                case 0x07:
                    homeFragmentQdmsImg.setImageResource(R.drawable.img_home_shushi);
                    homeFragmentQdmsText.setText(getString(R.string.routine_ssms));

                    break;
                case 0x08:
                    homeFragmentQdmsImg.setImageResource(R.drawable.img_home_rest);
                    homeFragmentQdmsText.setText(getString(R.string.routine_rest));
                    break;
                case 0x0c:
                    homeFragmentQdmsImg.setImageResource(R.drawable.img_home_cck);
                    homeFragmentQdmsText.setText(getString(R.string.routine_help));
                    if (CommandUtil.IS_ROLLOVEW_SHOCK) {
                        SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.CEFAN_STOP);
                        FinishActivityManager.getManager().finishActivity(RolloverShockNextActivity.class);
                    }
                    break;
                case 0x0e:
                    homeFragmentQdmsImg.setImageResource(R.drawable.img_home_zuida);
                    homeFragmentQdmsText.setText(getString(R.string.routine_zdcq));
                    if (CommandUtil.IS_ROLLOVEW_SHOCK) {
                        SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.CEFAN_STOP);
                        FinishActivityManager.getManager().finishActivity(RolloverShockNextActivity.class);
                    }
                    break;
            }
        }
    }

    /**
     * 返回数据识别0:放下，1：抬起
     */
    private void distinguish(byte[] bytes) {
        if (DistinguishUtil.distinguishUtil(bytes)) {
            switch (bytes[3]) {
                //护栏
                case 0:
                    switch (bytes[4]) {
                        case 0:
                            CommandUtil.RALL_ONE = false;
                            Log.d("yangshuohulan", "第一个放下");
                            break;
                        case 1:
                            CommandUtil.RALL_ONE = true;
                            Log.d("yangshuohulan", "第一个抬起");
                            break;
                    }
                    switch (bytes[5]) {
                        case 0:
                            CommandUtil.RALL_TWO = false;
                            Log.d("yangshuohulan", "第二个放下");
                            break;
                        case 1:
                            CommandUtil.RALL_TWO = true;
                            Log.d("yangshuohulan", "第二个抬起");
                            break;
                    }
                    switch (bytes[6]) {
                        case 0:
                            CommandUtil.RALL_THREE = false;
                            Log.d("yangshuohulan", "第三个放下");
                            break;
                        case 1:
                            CommandUtil.RALL_THREE = true;
                            Log.d("yangshuohulan", "第三个抬起");
                            break;
                    }
                    switch (bytes[7]) {
                        case 0:
                            CommandUtil.RALL_FOUR = false;
                            Log.d("yangshuohulan", "第四个放下");
                            break;
                        case 1:
                            CommandUtil.RALL_FOUR = true;
                            Log.d("yangshuohulan", "第四个抬起");
                            break;

                    }
                    if (CommandUtil.IS_LEFT_RIGHT_ANOTHER) {
                        retrievalType();
                    }
                    if (CommandUtil.IS_ROLLOVEW_SHOCK) {
                        retrievalCefan();
                    }
                    break;
                //床体角度
                case 1:
                    CommandUtil.HOUBEI_ISZERO = false;
                    switch (bytes[4]) {
                        //角度为负值
                        case 0:
                            mAngleFu = Integer.parseInt(bytes[5] + "");
                            CommandUtil.BED_AFTER = mAngleFu;
                            angleNumText.setText("-" + mAngleFu + "°");
                            homebedBed.setImageResource(R.drawable.img_homebed_negative);
                            break;
                        //角度为正值
                        case 1:

                            int mAngle = Integer.parseInt(bytes[5] + "");
                            CommandUtil.BED_FRONT = mAngle;
                            if (mAngle <= 3) {
                                angleNumText.setText(0 + "°");
                                homebedBed.setImageResource(R.drawable.img_homebed_one);
                                CommandUtil.HOUBEI_ISZERO = true;
                            } else if (mAngle <= 30) {
                                angleNumText.setText(mAngle + "°");
                                homebedBed.setImageResource(R.drawable.img_homebed_two_new);
                            } else if (mAngle <= 40) {
                                angleNumText.setText(mAngle + "°");
                                homebedBed.setImageResource(R.drawable.img_homebed_three);
                            } else if (mAngle <= 60) {
                                angleNumText.setText(mAngle + "°");
                                homebedBed.setImageResource(R.drawable.img_homebed_four);
                            } else if (mAngle <= 90) {
                                angleNumText.setText(mAngle + "°");
                                homebedBed.setImageResource(R.drawable.img_homebed_five);
                            }

                            int mFinalAngle = SPUtils.getInstance().getInt("bed_final_angle", 0);
                            switch (CommandUtil.HEAD_WARNING_TYPE) {
                                case 1:
                                    if (mAngle < 30) {
                                        startActivity(new Intent(MyApp.getAppContext(), WarningCenterActivity.class));
                                    }
                                    break;
                                case 2:
                                    if (mAngle < 45) {
                                        startActivity(new Intent(MyApp.getAppContext(), WarningCenterActivity.class));
                                    }
                                    break;
                            }
                            switch (CommandUtil.HEAD_WARNING_TYPE) {
                                case 1:
                                    if (mFinalAngle > 30) {
                                        SerialProtUtil.getInstance().sendBytes50(2, CommandUtil.HEAD_CLOSE_DIDI);
                                        FinishActivityManager.getManager().finishActivity(WarningCenterActivity.class);
//                                        CommandUtil.HEAD_WARNING_TYPE = 0;
                                    }
                                    break;
                                case 2:
                                    if (mFinalAngle > 45) {
                                        SerialProtUtil.getInstance().sendBytes50(2, CommandUtil.HEAD_CLOSE_DIDI);
                                        FinishActivityManager.getManager().finishActivity(WarningCenterActivity.class);
//                                        CommandUtil.HEAD_WARNING_TYPE = 0;
                                    }
                                    break;
                            }
                            SPUtils.getInstance().put("bed_final_angle", mAngle);
                            if (CommandUtil.IS_LEFT_RIGHT_ALL) {
                                retrievalType();
                            }
                            break;

                    }
                    switch (bytes[6]) {
                        case 0: //后倾负值
                            CommandUtil.CHUANGTI_ISZERO = false;
                            homeFragmentPingfangImg.setImageResource(R.drawable.img_home_pingfangimg_qian);
                            String mAngle = String.format(bytes[7] + "");
                            homeFragmentPingfang.setText(getText(R.string.home_houqing) + "    " + mAngle + "°");
                            if (Integer.parseInt(mAngle) <= 5) {
                                FinishActivityManager.getManager().finishActivity(RolloverShockCantStartActivity.class);
                            }
                            break;
                        case 1://前倾正值
                            if (Integer.parseInt(bytes[7] + "") <= 3) {
                                homeFragmentPingfangImg.setImageResource(R.drawable.img_home_pingfang_new);
                                homeFragmentPingfang.setText(getText(R.string.home_pingfang));
                                CommandUtil.CHUANGTI_ISZERO = true;
                            } else {
                                String mAngle1 = String.format(bytes[7] + "");
                                homeFragmentPingfang.setText(getText(R.string.home_qianqing) + "     " + mAngle1 + "°");
                                CommandUtil.CHUANGTI_ISZERO = false;
                                homeFragmentPingfangImg.setImageResource(R.drawable.img_home_pingfangimg_hou);
                                if (CommandUtil.BED_FRONT == 0) {
                                    homebedBed.setImageResource(R.drawable.img_homebed_qq);
                                }

                            }

                            break;
                    }
                    if (CommandUtil.IS_LEFT_RIGHT_ALL) {
                        retrievalType();
                    }
                    break;
                //病床位置已锁定
                case 2:
                    startActivity(new Intent(MyApp.getAppContext(), BedPosLockActivity.class));
                    break;
                //启用脚踏板
                case 3:
                    Intent intent = new Intent();
                    intent.putExtra("colorType", 1);
                    intent.setClass(MyApp.getAppContext(), WarningLeftTopActivity.class);
                    startActivity(intent);
                    break;
                //已启用脚踏板
                case 4:
                    Intent intent2 = new Intent();
                    intent2.putExtra("colorType", 0);
                    intent2.setClass(MyApp.getAppContext(), WarningLeftTopActivity.class);
                    startActivity(intent2);
                    break;
                case 5:
                    weightOne = bytes[4];
                    weightTwo = bytes[5];
                    weightThree = bytes[6];
                    weightfour = bytes[7];
                    weightAll = bytes[8];
                    Log.d("yangshuo", weightOne + "---" + weightTwo + "---" + weightThree + "---" + weightAll);
                    if (3 == CommandUtil.LEAVEBED_TYPE) {
                        if (weightAll < 30) {
                            SerialProtUtil.getInstance().sendBytes50(2, CommandUtil.GET_WEIGHT_LEAVE_STOP);
                            startActivity(new Intent(MyApp.getAppContext(), LeaveBedNoVoiceActivity.class));
                            break;
                        }
                    } else {
                        if (weightAll > 30) {
                            int transverseLeft, transverseRight, verticalUp, verticalDown;
                            transverseLeft = weightOne + weightfour;
                            transverseRight = weightTwo + weightThree;
                            verticalUp = weightOne + weightTwo;
                            verticalDown = weightThree + weightfour;
                            if (transverseRight - transverseLeft >= CommandUtil.WARNING_DEVIATION || transverseLeft - transverseRight >= CommandUtil.WARNING_DEVIATION || verticalUp - verticalDown >= CommandUtil.WARNING_DEVIATION || verticalDown - verticalUp >= CommandUtil.WARNING_DEVIATION) {
                                SerialProtUtil.getInstance().sendBytes50(2, CommandUtil.GET_WEIGHT_LEAVE_STOP);
                                startActivity(new Intent(MyApp.getAppContext(), LeaveBedNoVoiceActivity.class));
                            }
                            break;
                        } else {
                            CommandUtil.LEAVEBED_TYPE = 0;
                            SerialProtUtil.getInstance().sendBytes50(2, CommandUtil.GET_WEIGHT_LEAVE_STOP);
                            startActivity(new Intent(MyApp.getAppContext(), WeightTooSmallActivity.class));

                        }
                    }
            }
        }
    }

    /**
     * 检索后背护栏状态
     */
    private void retrievalType() {
        if (CommandUtil.RALL_ONE && CommandUtil.RALL_TWO && CommandUtil.RALL_THREE && CommandUtil.RALL_FOUR && CommandUtil.BED_FRONT < 40 && CommandUtil.BED_AFTER < 25) {

        } else {
            if (CommandUtil.IS_LEFT_RIGHT_ANOTHER) {
                SerialProtUtil.getInstance().sendBytes300(2, CommandUtil.PAUSE_CRFAN);
                startActivity(new Intent(MyApp.getAppContext(), RolloverShockCantStartActivity.class));
            }
        }
    }

    /**
     * 检索左右翻护栏状态
     */
    private void retrievalCefan() {
//        Log.d("yangshuo",CommandUtil.RALL_ONE+""+CommandUtil.RALL_TWO+CommandUtil.RALL_THREE+CommandUtil.RALL_FOUR+"");
        if (CommandUtil.RALL_ONE && CommandUtil.RALL_TWO && CommandUtil.RALL_THREE && CommandUtil.RALL_FOUR) {
            startActivity(new Intent(MyApp.getAppContext(), NeedResumeActivity.class));
        } else {
            FinishActivityManager.getManager().finishActivity(RolloverShockNextActivity.class);
            SerialProtUtil.getInstance().sendBytes200(2, CommandUtil.CEFAN_STOP);
            startActivity(new Intent(MyApp.getAppContext(), RolloverShockCantStartActivity.class));
        }
    }

    private Disposable mTimeCountDisposableFS;

    public void TimeCountFS() {
        //0-count依次输出，延时0s执行，每1s发射一次。
        mTimeCountDisposableFS = Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(aLong -> {

                })
                .doOnComplete(() -> {
                    homeFragmentZeroimg.setImageResource(R.drawable.imf_home_zero_off);
                    CommandUtil.ZERO_TYPE = 3;
                    if (mTimeCountDisposableFS != null) {
                        mTimeCountDisposableFS.dispose();
                    }
                })
                .subscribe();
    }
}
